package part21线程.线程同步;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class 同步Lock锁2 {

	public static void main(String[] args) {

		// 新建线程
		卖票5 m = new 卖票5(); // Runnable接口的实现类
		// 进入就绪
		new Thread(m).start();
		new Thread(m).start();
		new Thread(m).start();
	}

}

/**
 * 卖票类，实现多线程和同步锁Lock
 * 
 * @author Administrator
 *
 */
class 卖票5 implements Runnable {
	private int piao = 10; // 10张票
	// 声明锁对象
	public Lock lock = new ReentrantLock();

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			// 调用卖票的方法
			saleTicket();
		}
	}
	public void saleTicket() {
		// 上锁
		lock.lock();
		try {
			if (piao > 0) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// 提示
				System.out.println(Thread.currentThread().getName() + "抢到票号：" + (piao--));
			}
		} finally {
			// 释放锁
			lock.unlock();
		}
	}
}